package com.ljl.service;

import com.alibaba.fastjson.JSONObject;
import com.ljl.config.BaiduProperties;
import com.ljl.entity.FaceDetectResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

/**
 * @author 刘家良
 * @date 2022/10/30 16:46
 * @description
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class BaiduService {

    private final BaiduProperties baiduProperties;
    private final RestTemplate restTemplate;

    /**
     * 获取百度api调用凭证
     * @return /
     */
    private String getAccessToken() {
        String url = "https://aip.baidubce.com/oauth/2.0/token";
        url = url + "?grant_type=client_credentials&client_id=" + baiduProperties.getApiKey() + "&client_secret=" + baiduProperties.getSecretKey();
        JSONObject forObject = restTemplate.getForObject(url, JSONObject.class);
        return forObject.getString("access_token");
    }

    /**
     * 人脸检测
     * @param imgBase64 图片的base64
     * @return 调用结果/
     */
    public FaceDetectResponse faceDetect(String imgBase64) {
        String url = "https://aip.baidubce.com/rest/2.0/face/v3/detect";
        url = url + "?access_token=" + getAccessToken();
        JSONObject req = new JSONObject();
        req.put("image_type", "BASE64");
        req.put("image", imgBase64);
        req.put("face_field", "age,emotion,gender,expression");
        req.put("max_face_num", 10);
        String res = restTemplate.postForObject(url, req, String.class);
        JSONObject result = JSONObject.parseObject(res).getJSONObject("result");
        return result.toJavaObject(FaceDetectResponse.class);
    }

}
